//
//  XMLParser.m
//  eBaySearch
//
//  Created by Dang Duc Nam (namk42c@yahoo.com) on 4/29/09.
//  Copyright 2009 Unitech. All rights reserved.
//

#import "XMLParser.h"
#import "XMLAppDelegate.h"
#import "eBayItem.h"

@implementation XMLParser
@synthesize currentItem;
@synthesize currentProperty;
@synthesize currentShippingCostSummary;
@synthesize currentShippingCurrency;
- (XMLParser *) initXMLParser {
	
	[super init];
	
	appDelegate = (XMLAppDelegate *)[[UIApplication sharedApplication] delegate];
	appDelegate.list = [[NSMutableArray alloc] init];
	return self;
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (self.currentProperty) {
        [self.currentProperty appendString:string];
		//NSLog(@"appendString:%@",string);
    }
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    if (qName) {
        elementName = qName;
    }
    if (self.currentShippingCostSummary) { // Are we in a
        // Check for standard nodes
        if ([elementName isEqualToString:@"ShippingServiceCost"] || [elementName isEqualToString:@"ShippingType"]) {
            self.currentProperty = [NSMutableString string];
			if ([elementName isEqualToString:@"ShippingServiceCost"]) {
				self.currentShippingCurrency = [attributeDict valueForKey:@"currencyID"];
			}
        }
	} else if (self.currentItem) { // Are we in a  ?
        // Check for standard nodes
        if ([elementName isEqualToString:@"TimeLeft"] || [elementName isEqualToString:@"ListingStatus"] || [elementName isEqualToString:@"BidCount"] || [elementName isEqualToString:@"PrimaryCategoryName"] || [elementName isEqualToString:@"EndTime"] || [elementName isEqualToString:@"ItemID"] || [elementName isEqualToString:@"ViewItemURLForNaturalSearch"] || [elementName isEqualToString:@"Title"] || [elementName isEqualToString:@"ConvertedCurrentPrice"] || [elementName isEqualToString:@"GalleryURL"]) {
            self.currentProperty = [NSMutableString string];
			// Check for deeper nested node
        } else if ([elementName isEqualToString:@"ShippingCostSummary"]) {
            self.currentShippingCostSummary = [[ShippingCostSummary alloc] init]; // Create the element
			//NSLog(@"Create the element");
        }
    } if ([elementName isEqualToString:@"Item"]) { // We are outside of everything, so we need a
        // Check for deeper nested node
		self.currentItem = [[eBayItem alloc] init];
		//NSLog(@"New Item");
    }
	
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if (qName) {
        elementName = qName;
    }

    if (self.currentShippingCostSummary) { // Are we in a
        // Check for standard nodes
        if ([elementName isEqualToString:@"ShippingServiceCost"]) {
            self.currentShippingCostSummary.ShippingServiceCost = self.currentProperty;
			self.currentShippingCostSummary.ShippingCurrency = self.currentShippingCurrency;
        } else if ([elementName isEqualToString:@"ShippingType"]) {
			self.currentShippingCostSummary.ShippingType = self.currentProperty;
		} else if ([elementName isEqualToString:@"ShippingCostSummary"]) {
			//NSLog(@"Add cost to item");
			self.currentItem.shippingCostSummary = currentShippingCostSummary;
            self.currentShippingCostSummary = nil; // Set nil
        }
	} else if (self.currentItem) { // Are we in a  ?
        if ([elementName isEqualToString:@"ConvertedBuyItNowPrice"]) {
            self.currentItem.buyitnowprice = self.currentProperty;
        } else if ([elementName isEqualToString:@"ViewItemURLForNaturalSearch"]) {
            self.currentItem.viewItemURL = self.currentProperty;
		} else if ([elementName isEqualToString:@"ConvertedCurrentPrice"]) {
            self.currentItem.price = self.currentProperty;
		} else if ([elementName isEqualToString:@"ItemID"]) {
            self.currentItem.itemID = self.currentProperty;
		} else if ([elementName isEqualToString:@"GalleryURL"]) {
            self.currentItem.galleryURL = self.currentProperty;
		} else if ([elementName isEqualToString:@"Title"]) {
            self.currentItem.title = self.currentProperty;
		} else if ([elementName isEqualToString:@"ListingStatus"]) {
            self.currentItem.status = self.currentProperty;
		} else if ([elementName isEqualToString:@"EndTime"]) {
            self.currentItem.endtime = self.currentProperty;
		} else if ([elementName isEqualToString:@"TimeLeft"]) {
            self.currentItem.timeleft = self.currentProperty;
		} else if ([elementName isEqualToString:@"PrimaryCategoryName"]) {
            self.currentItem.category = self.currentProperty;
		} else if ([elementName isEqualToString:@"BidCount"]) {
            self.currentItem.bidcount = self.currentProperty;
		} else if ([elementName isEqualToString:@"Item"]) {
			NSLog(@"Added item to array: %@",self.currentItem.title);
			NSURL *url = [NSURL URLWithString:currentItem.galleryURL];
			UIImage *img = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
			currentItem.image = [self compressImageDownToPhoneScreenSize:img];
			[appDelegate.list addObject:currentItem];
			[appDelegate performSelectorOnMainThread:@selector(reloadTable) withObject:nil waitUntilDone:NO];
			[currentItem release];
			currentItem = nil;
		}
	}
    // We reset the currentProperty, for the next textnodes..
    self.currentProperty = nil;
}
//	==============================================================
//	resizedImage
//	==============================================================
// Return a scaled down copy of the image.  
-(UIImage*)compressImageDownToPhoneScreenSize:(UIImage*)theImage{
	
	UIImage * bigImage = theImage;
	
	float actualHeight = bigImage.size.height;
	float actualWidth = bigImage.size.width;
	
	float imgRatio = actualWidth / actualHeight;

	imgRatio = 55.0 / actualHeight;
	actualWidth = imgRatio * actualWidth;
	actualHeight = 50.0;
	
	CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
	UIGraphicsBeginImageContext(rect.size);
	[bigImage drawInRect:rect];  // scales image to rect
	theImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	//RETURN
	return theImage;
	
}

- (void) dealloc {
	
	[item release];
	[currentItem release];
	[currentProperty release];
	[super dealloc];
}

@end
